package com.hulk.dryad.admin.websocket;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hulk.dryad.common.constant.CommonConstants;
import com.hulk.dryad.common.util.SpringContextHolder;
import com.hulk.dryad.manage.framework.datasource.DynamicDataSourceHolder;
import com.hulk.dryad.manage.framework.websocket.common.principal.WsPrincipal;
import com.hulk.dryad.manage.framework.websocket.server.handshake.WebSocketPrincipalResolve;
import com.hulk.dryad.persistence.entity.SysUserModel;
import com.hulk.dryad.admin.service.SysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.time.LocalDateTime;

/**
 * 默认的 Principal 解析
 *
 * @author
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AdminWebSocketPrincipalResolve implements WebSocketPrincipalResolve {

	private static final  String nameToken = HttpHeaders.AUTHORIZATION;
	private static final  String nameTenant = CommonConstants.TENANT_ID;


	@Nullable
	@Override
	public Principal resolve(ServerHttpRequest request) {
		HttpServletRequest  httpServletRequest = ((ServletServerHttpRequest)request).getServletRequest();
		String token = httpServletRequest.getParameter(nameToken);
		String tenant = httpServletRequest.getParameter(nameTenant);
		if(StrUtil.isBlank(tenant) || StrUtil.isBlank(token)){
			return null;
		}
		setTenantContext(tenant);
		SysUserModel authUser = findUserByToken(token);
		if (authUser != null) {
			return new WsPrincipal(authUser.getUsername(),tenant);
		}
		return null;
	}

	/**
	 * 设置租户上下文,可用于选择数据源
	 */
	private void setTenantContext(String tenant) {
		DynamicDataSourceHolder.set(tenant);
	}

	/**
	 * 获取握手的账号
	 */
	private SysUserModel findUserByToken(String token) {
		LocalDateTime currentTime = LocalDateTime.now();
		LambdaQueryWrapper<SysUserModel> qw = Wrappers.<SysUserModel>lambdaQuery()
				.eq(SysUserModel::getToken, token)
				.gt(SysUserModel::getTokenExpireTime, currentTime);
		SysUserService	sysUserService =SpringContextHolder.getBean(SysUserService.class);
		return sysUserService.getOne(qw);
	}

}





